//
//  TwitterHelper.m
//  mytcom
//
//  Created by Le Lam on 2/17/11.
//  Copyright 2011 Seta:Cinq VN. All rights reserved.
//

#import "TwitterHelper.h"
#import "JSON.h"

#define kTwitterConsumerKey			@"Jst7t215yKB8QtNWABGw"
#define kTwitterConsumerSecret		@"6C8PTpDfSqkw6RaQuUUsvXswiAdpIHL3yjt5qSQwI"
#define kTwitterRedirectURL			@"http://dev.twitter.com"
#define kTwitpicAPIKey				@"6f4c2da46f38cd3edcc08d764db706db"

#define kTwitterAccessTokenKey		@"kTwitterAccessTokenKey"
#define kTwitterAccessTokenSecret	@"kTwitterAccessTokenSecret"

@interface TwitterHelper(private)

- (void)requestRequestToken;
- (void)requestAccessToken;

@end

@implementation TwitterHelper

@synthesize authorizeWebView;
@synthesize accessToken;
@synthesize consumer;
@synthesize publicDelegate;

- (id)init {
	self = [super init];
	if (self) {
		NSString *accessTokenKey = [[NSUserDefaults standardUserDefaults] objectForKey:kTwitterAccessTokenKey];
		NSString *accessTokenSecret = [[NSUserDefaults standardUserDefaults] objectForKey:kTwitterAccessTokenSecret];
		OAToken *_accessToken = [[OAToken alloc] initWithKey:accessTokenKey secret:accessTokenSecret];
		OAConsumer *_consumer = [[OAConsumer alloc] initWithKey:kTwitterConsumerKey secret:kTwitterConsumerSecret];
		self.accessToken = _accessToken;
		self.consumer = _consumer;
		[_accessToken release];
		[_consumer release];
		currentMethod = [[NSMutableString alloc] initWithString:@""];
	}
	return self;
}

- (void)dealloc {
	
	[super dealloc];
}

- (void)authorize {
	[self requestRequestToken];
}

+ (BOOL)isAuthorized {
	return ([[NSUserDefaults standardUserDefaults] valueForKey:kTwitterAccessTokenKey] != nil);
}

+ (void)deleteCredential {
	[[NSUserDefaults standardUserDefaults] removeObjectForKey:kTwitterAccessTokenKey];
	[[NSUserDefaults standardUserDefaults] removeObjectForKey:kTwitterAccessTokenSecret];
	[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"twUsername"];
	[[NSUserDefaults standardUserDefaults] synchronize];
	
	NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *each in cookieStorage.cookies) {
		if ([[each domain] rangeOfString:@"twitter"].length > 0) {
			[cookieStorage deleteCookie:each];
		}
    }
}

- (void)requestRequestToken {
	consumer = [[OAConsumer alloc] initWithKey:kTwitterConsumerKey secret:kTwitterConsumerSecret];
	NSURL *url = [NSURL	URLWithString:@"https://twitter.com/oauth/request_token"];
	OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
																   consumer:consumer
																	  token:nil
																	  realm:nil
														  signatureProvider:nil];
	[request setHTTPMethod:@"POST"];
	OADataFetcher *fetcher = [[OADataFetcher alloc] init];
	[fetcher fetchDataWithRequest:request
						 delegate:self
				didFinishSelector:@selector(requestTokenTicket:didFinishWithData:) 
				  didFailSelector:@selector(requestTokenTicket:didFailWithError:)];
	[request release];
}

- (void)requestTokenTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data {
	if (ticket.didSucceed) {
		NSString *responseBody = [[NSString alloc] initWithData:data
													   encoding:NSUTF8StringEncoding];
		requestToken = [[OAToken alloc] initWithHTTPResponseBody:responseBody];
		NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?oauth_token=%@", @"https://api.twitter.com/oauth/authorize", requestToken.key]];
		[authorizeWebView setDelegate:self];
		[authorizeWebView loadRequest:[NSURLRequest requestWithURL:url]];
		[responseBody release];
	}
}

- (void)requestTokenTicket:(OAServiceTicket *)ticket didFailWithError:(NSError *)error {
	NSLog(@"%@", [error description]);
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
	if ([[[request URL] absoluteString] rangeOfString:kTwitterRedirectURL].location != NSNotFound) {
		NSMutableDictionary	*queryParams = nil;
		if (request.URL.query != nil) {
			queryParams = [NSMutableDictionary dictionaryWithCapacity:0];
			NSArray	*vars = [request.URL.query componentsSeparatedByString:@"&"];
			NSArray	*parts;
			for (NSString *var in vars) {
				parts = [var componentsSeparatedByString:@"="];
				if (parts.count == 2) {
					[queryParams setObject:[parts objectAtIndex:1] forKey:[parts objectAtIndex:0]];
				}
			}
		}
		responseQueryVars = [queryParams copy];
		if (webView.superview) {
			[webView removeFromSuperview];
		}
		[self requestAccessToken];
		
		return NO;
	}
	
	return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
	if (loadingIndicator == nil) {
		loadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
		loadingIndicator.hidesWhenStopped = YES;
		CGRect _frame = loadingIndicator.frame;
		_frame.origin.x = (webView.frame.size.width - _frame.size.width) / 2;
		_frame.origin.y = (webView.frame.size.height - _frame.size.height) / 2;
		loadingIndicator.frame = _frame;
		[webView addSubview:loadingIndicator];
	}
	[loadingIndicator startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
	if (loadingIndicator != nil) {
		[loadingIndicator stopAnimating];
	}
}

- (void)requestAccessToken {
	NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/oauth/access_token"];
	OAMutableURLRequest	*request = [[OAMutableURLRequest alloc] initWithURL:url consumer:consumer token:requestToken realm:nil signatureProvider:nil];
	[request setHTTPMethod:@"POST"];
	OAAsynchronousDataFetcher *fetcher = [OAAsynchronousDataFetcher asynchronousFetcherWithRequest:request
																						  delegate:self
																				 didFinishSelector:@selector(tokenAccessTicket:didFinishWithData:)
																				   didFailSelector:@selector(tokenAccessTicket:didFailWithError:)];
	[fetcher start];
	[request release];
}

- (void)tokenAccessTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data {
	if (ticket.didSucceed) {
		NSString	*respondeBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
		
		NSString *screen_name = [respondeBody substringFromIndex:[respondeBody rangeOfString:@"screen_name="].location + 12];
		
		//Save username
		[[NSUserDefaults standardUserDefaults] setObject:screen_name forKey:@"twUsername"];
		[[NSUserDefaults standardUserDefaults] synchronize];
		
		accessToken = [[OAToken alloc] initWithHTTPResponseBody:respondeBody];
		[respondeBody release];
		[[NSUserDefaults standardUserDefaults] setObject:accessToken.key forKey:kTwitterAccessTokenKey];
		[[NSUserDefaults standardUserDefaults] setObject:accessToken.secret forKey:kTwitterAccessTokenSecret];
		[[NSUserDefaults standardUserDefaults] synchronize];
		[[NSNotificationCenter defaultCenter] postNotificationName:kTwitterDidAuthorize object:nil];
	}
}

- (void)tokenAccessTicket:(OAServiceTicket *)ticket didFailWithError:(NSError *)error {
	NSLog(@"%@", [error description]);
}

- (void)sendStatus:(NSString *)status {
	[currentMethod setString:@"public"];
	/*
	OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://api.twitter.com/1/statuses/update.json"]
																	consumer:consumer
																	   token:accessToken
																	   realm:nil
														   signatureProvider:nil];
	
	[request setHTTPMethod:@"POST"];
	
	OARequestParameter *statusParam = [[OARequestParameter alloc] initWithName:@"status"
																		 value:status];
	NSArray *params = [NSArray arrayWithObjects:statusParam, nil];
	[request setParameters:params];
	[statusParam release];
	
	NSURLConnection *connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
	[connection start];
	[request release];
	 */
	 OAMutableURLRequest *oRequest = [[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.twitter.com/1/statuses/update.json"]
	 consumer:consumer
	 token:accessToken
	 realm:nil
	 signatureProvider:nil];
	 
	 [oRequest setHTTPMethod:@"POST"];
	 
	 OARequestParameter *statusParam = [[OARequestParameter alloc] initWithName:@"status"
	 value:status];
	 NSArray *params = [NSArray arrayWithObjects:statusParam, nil];
	 [oRequest setParameters:params];
	 [statusParam release];
	 
	 OAAsynchronousDataFetcher *fetcher = [OAAsynchronousDataFetcher asynchronousFetcherWithRequest:oRequest
	 delegate:self
	 didFinishSelector:@selector(sendStatusTicket:didFinishWithData:)
	 didFailSelector:@selector(sendStatusTicket:didFailWithError:)];	
	 
	 [fetcher start];
	 [oRequest release];
	
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    if (publicDelegate && [(NSObject *)publicDelegate respondsToSelector:@selector(publicError:)]) {
        [publicDelegate publicError:error];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if (publicDelegate && [(NSObject *)publicDelegate respondsToSelector:@selector(publicComplete)])  {
        [publicDelegate publicComplete];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	if (responseData != nil) {
		[responseData release];
	}
	responseData = nil;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	if (responseData == nil) {
		responseData = [[NSMutableData alloc] init];
	}
	[responseData appendData:data];
}

- (void)sendStatusTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data 
{	
	if (publicDelegate && [(NSObject *)publicDelegate respondsToSelector:@selector(publicComplete)]) {
		[publicDelegate publicComplete];
	}
}

- (void)sendStatusTicket:(OAServiceTicket *)ticket didFailWithError:(NSError*)error
{
	if (publicDelegate && [(NSObject *)publicDelegate respondsToSelector:@selector(publicError:)]) {
		[publicDelegate publicError:error];
	}
}

@end
